package com.ruoyi.lottery.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.lottery.domain.LotActivityLotTask;
import com.ruoyi.lottery.domain.LotTaskUser;
import com.ruoyi.lottery.domain.LotTimes;
import com.ruoyi.lottery.mapper.LotActivityLotTaskMapper;
import com.ruoyi.lottery.mapper.LotTaskUserMapper;
import com.ruoyi.lottery.mapper.LotTimesMapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.lottery.mapper.LotTaskMapper;
import com.ruoyi.lottery.domain.LotTask;
import com.ruoyi.lottery.service.ILotTaskService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 抽奖任务Service业务层处理
 *
 * @author shier
 * @date 2023-01-27
 */
@Service
public class LotTaskServiceImpl extends ServiceImpl<LotTaskMapper, LotTask> implements ILotTaskService {

    @Resource
    private LotTaskUserMapper           lotTaskUserMapper;
    @Resource
    private LotActivityLotTaskMapper    lotActivityLotTaskMapper;
    @Resource
    private LotTimesMapper              lotTimesMapper;

    /**
     * 查询抽奖任务列表
     *
     * @param lotTask 抽奖任务
     * @return 抽奖任务
     */
    @Override
    public List<LotTask> selectLotTaskList(LotTask lotTask) {
        return getBaseMapper().selectLotTaskList(lotTask);
    }


    @Override
    public List<LotTask> waitTasksByLoginUser() {

        // TODO: 假设当前用户的ID为1, 用户类型为老用户
        int currentUserParticipationLimit = 1;

        // 0: 代办任务集合
        List<LotTask> waitFulfillTask = new ArrayList<>();

        // 1: 查询 所有用户都能完成的任务(我没有完成的)
        this.waitTaskByUserIdAndParticipationLimit(1L, LotTask.PARTICIPATION_LIMIT_ALL_USER, waitFulfillTask);

        // 2: 基于用户的类型(0: 新用户; 1: 老用户)查询任务
        if (LotTask.PARTICIPATION_LIMIT_NEW_USER == currentUserParticipationLimit) {
            // 1: 查询 新用户都能完成的任务(我没有完成的)
            this.waitTaskByUserIdAndParticipationLimit(1L, LotTask.PARTICIPATION_LIMIT_NEW_USER, waitFulfillTask);
        } else {
            // 1: 查询 老用户都能完成的任务(我没有完成的)
            this.waitTaskByUserIdAndParticipationLimit(1L, LotTask.PARTICIPATION_LIMIT_OLD_USER, waitFulfillTask);
        }

        return waitFulfillTask;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String taskFulfill(Long waitTaskId) {
        // TODO: 假设当前用户的ID为1, 用户类型为老用户
        int currentUserParticipationLimit = 1;

        String msg = "恭喜你任务以完成";

        // 1: 任务-用户中间表 查看 是否存在该数据: 存在表示已经完成过了,返回提示信息
        LambdaQueryWrapper<LotTaskUser> wrapper = Wrappers.lambdaQuery(LotTaskUser.class)
                .eq(LotTaskUser::getUserId, 1L)
                .eq(LotTaskUser::getTaskId, waitTaskId);
        LotTaskUser isExist = lotTaskUserMapper.selectOne(wrapper);

        if (isExist != null) {
            // 表示已经完成过了,直接返回提示信息
            return "你已经完成过了该任务,不能在完成";
        }

        // 2: 完成任务:创建 任务-用户中间表对象,并新增
        LotTaskUser lotTaskUser = new LotTaskUser();
        lotTaskUser.setUserId(1L);
        lotTaskUser.setTaskId(waitTaskId);
        lotTaskUser.setNumberLimit(this.getById(waitTaskId).getNumberLimit());
        lotTaskUserMapper.insert(lotTaskUser);


        // 3: 完成任务之后,得到相应的 活动ID集合
        LambdaQueryWrapper<LotActivityLotTask> actTaskWrapper = Wrappers.lambdaQuery(LotActivityLotTask.class).eq(LotActivityLotTask::getTaskId, waitTaskId);
        List<LotActivityLotTask> actTasks = lotActivityLotTaskMapper.selectList(actTaskWrapper);
        List<Long> actIds = actTasks.stream().map(LotActivityLotTask::getActivityId).collect(Collectors.toList());

        // 4: 根据 活动ID&用户ID 抽奖次数+1
        for (Long actId : actIds) {
            LambdaQueryWrapper<LotTimes> lotTimesWrapper = Wrappers.lambdaQuery(LotTimes.class)
                    .eq(LotTimes::getActivityId, actId)
                    .eq(LotTimes::getUserId, 1);
            LotTimes lotTimes = lotTimesMapper.selectOne(lotTimesWrapper);

            if (lotTimes != null) {
                // 表示以前就有数据,并且次数+1
                lotTimes.setLotteryTimes(lotTimes.getLotteryTimes() + 1);
                lotTimesMapper.updateById(lotTimes);
            } else {
                // 以前没有数据
                LotTimes temp = new LotTimes();
                temp.setActivityId(actId);
                temp.setUserId(1L);
                temp.setLotteryTimes(1);
            }
        }
        return msg;
    }

    private void waitTaskByUserIdAndParticipationLimit(Long loginUserId, int participationLimit, List<LotTask> waitTask) {
        // 1: 基于 参与限制(新老全部用户) 查询任务
        LambdaQueryWrapper<LotTask> wrapper = Wrappers.lambdaQuery(LotTask.class).eq(LotTask::getParticipationLimit, participationLimit);
        List<LotTask> lotTasks = super.list(wrapper);

        // 1.1: 使用迭代器 ===> 如果当前用户已经完成了该任务就删除该任务
        Iterator<LotTask> it = lotTasks.iterator();
        while (it.hasNext()) {
            LotTask lotTask = it.next();

            // 基于 任务ID&当前登录用户ID 去任务-用户中间表去查完成了的
            LambdaQueryWrapper<LotTaskUser> centreTableWrapper = Wrappers.lambdaQuery(LotTaskUser.class).eq(LotTaskUser::getUserId, loginUserId).eq(LotTaskUser::getTaskId, lotTask.getId());
            LotTaskUser lotTaskUser = lotTaskUserMapper.selectOne(centreTableWrapper);

            // 如果中间表对象 != null ===> 当前用于已经完成了该任务
            if (lotTaskUser != null) {
                // 删除完成了的任务
                it.remove();
            }
        }

        // 1.2: 把没有完成的任务添加进待办任务集合
        waitTask.addAll(lotTasks);
    }
}
